/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-01-02
 * Time:15:30
 */

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 通过这个来封装 DataSource
 */

public class DBUtil {
    private static volatile DataSource dataSource = null;

    private static DataSource getDataSource(){
        //双重校验锁，第一次判断是否需要加锁
        if (dataSource == null){
            synchronized (DBUtil.class){
                //第二次判定是否需要创建对象
                if (dataSource == null){
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_project?characterEncoding=utf8&useSSL=false");
                    ((MysqlDataSource)dataSource).setUser("root");
                    ((MysqlDataSource)dataSource).setPassword("wgz20030828");

                }
            }
        }
        return dataSource;
    }
    //建立连接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }
    //释放资源
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
